package org.ssssssss.curd.starter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.ssssssss.curd.controller.MagicGenCrudController;
import org.ssssssss.curd.generator.MagicApiCurdGenerator;
import org.ssssssss.curd.strategy.MysqlGetTableMetaStrategy;
import org.ssssssss.curd.strategy.RouteGetTableMetaStrategy;
import org.ssssssss.curd.util.MagicApiCurdSpringUtil;
import org.ssssssss.magicapi.core.config.MagicPluginConfiguration;
import org.ssssssss.magicapi.core.model.Plugin;
import org.ssssssss.magicapi.core.web.MagicControllerRegister;
import org.ssssssss.magicapi.datasource.model.DataSourceInfo;
import org.ssssssss.magicapi.datasource.model.MagicDynamicDataSource;

@Configuration
public class MagicCurdConfiguration  implements MagicPluginConfiguration {

    @Autowired
    private MagicDynamicDataSource magicDynamicDataSource;

    @Override
    public Plugin plugin() {
        return new Plugin("快速生成表CURD接口");
    }


    @Override
    public MagicControllerRegister controllerRegister() {
        return (mapping, configuration) -> mapping.registerController(new MagicGenCrudController(configuration));
    }

    /**
     * 全局路由获取表元信息策略
     * @param dataSourceInfo magic-api 数据源对象
     * @param magicDynamicDataSource magic-api 动态数据源对象
     */
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RouteGetTableMetaStrategy routeGetTableMetaStrategy(DataSourceInfo dataSourceInfo,
                                                               MagicDynamicDataSource magicDynamicDataSource){
        RouteGetTableMetaStrategy routeGetTableMetaStrategy = new RouteGetTableMetaStrategy(dataSourceInfo);
        routeGetTableMetaStrategy.setMagicDynamicDataSource(magicDynamicDataSource);
        return routeGetTableMetaStrategy;
    }

    /**
     *
     * @param dataSource
     * @return
     */
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public MysqlGetTableMetaStrategy mysqlGetTableMetaStrategy(MagicDynamicDataSource.DataSourceNode dataSource){
        return new MysqlGetTableMetaStrategy(dataSource);
    }

    @Bean
    @ConditionalOnMissingBean(MagicApiCurdSpringUtil.class)
    public MagicApiCurdSpringUtil magicApiCurdSpringUtil(){
        return new MagicApiCurdSpringUtil();
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public MagicApiCurdGenerator magicApiCurdGenerator(DataSourceInfo dataSourceInfo,String tableName){
        return new MagicApiCurdGenerator(dataSourceInfo,tableName);
    }
}
